-- ======================================================================
-- Hell Logic Sniffer Addon 
-- 
-- Copyright 2013 Hell-Prototypes
--
-- http://www.hellprototypes.com/
-- ======================================================================

PeriodNumber = require "Addon.PeriodNumber"

ModuleClass = "LS_PLUGIN"
ModuleName  = "FreqCounter"
ModuleTip   = "Calculate the frequency within two cursor"

function main ()
	local g_sampling_period = -1
	local g_left_cursor_index = -1
	local g_right_cursor_index = -1
	local g_curr_ch_num = -1

	PeriodNumber.get_period_number(LS_API)
	local param = PeriodNumber.get_param()
	
	if type(param) ~= "table" then
		LS_API.DebugMsg("param's type : " .. type(param))
		return
	end
	
	g_sampling_period = param[1]
	g_left_cursor_index = param[2]
	g_right_cursor_index = param[3]
	g_curr_ch_num = param[4]
	
	local failling_edge_count = PeriodNumber.get_period_number(LS_API)
	if failling_edge_count < 0 then
		return
	end
	
	local total_time_ns = (g_right_cursor_index - g_left_cursor_index) * g_sampling_period
	local total_time_us = total_time_ns/1000
	local total_time_ms = total_time_us/1000
	local freq_Hz = (1000*1000*1000 * failling_edge_count) / total_time_ns
	local freq_KHz = freq_Hz/1000
	local freq_MHz = freq_KHz/1000
	local time = string.format("= Total time = %.1fns = %.2fus = %.3fms", total_time_ns, total_time_us, total_time_ms)
	local freq = string.format("= Frequency = %.1fHz = %.3fKHz = %.3fMHz",  freq_Hz, freq_KHz, freq_MHz)

	LS_API.ReportPushBack("")
	LS_API.ReportPushBack("= FreqCounter Plugin Report:======================")
	LS_API.ReportPushBack(freq)
	LS_API.ReportPushBack(time)
	LS_API.ReportPushBack("==================================================")
end

